package com.game;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("cart.jsp").forward(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");

        if (userId == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        int gameId = Integer.parseInt(request.getParameter("gameId"));

        CartDAO cartDAO = new CartDAO();
        if ("add".equals(action)) {
            cartDAO.addToCart(userId, gameId);
        } else if ("remove".equals(action)) {
            cartDAO.removeCartItem(userId, gameId);
        } else if ("update".equals(action)) {
            int quantity = Integer.parseInt(request.getParameter("quantity"));
            cartDAO.updateCartItem(userId, gameId, quantity);
        }

        response.sendRedirect("cart.jsp");
    }
}